<template>
  <el-dialog
    v-model="visible"
    title="编辑日程"
    :width="dialogWidth"
    :class="{ 'mobile-dialog': isMobile }"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      @submit.prevent="handleSubmit"
    >
      <el-row :gutter="16">
        <el-col :xs="24" :sm="24">
          <el-form-item label="日程标题" prop="title">
            <el-input
              v-model="formData.title"
              placeholder="请输入日程标题"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <el-col :xs="24" :sm="12">
          <el-form-item label="开始时间" prop="start_time">
            <el-date-picker
              v-model="formData.start_time"
              type="datetime"
              placeholder="选择开始时间"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        
        <el-col :xs="24" :sm="12">
          <el-form-item label="结束时间" prop="end_time">
            <el-date-picker
              v-model="formData.end_time"
              type="datetime"
              placeholder="选择结束时间"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <el-col :xs="24" :sm="12">
          <el-form-item label="状态" prop="status">
            <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
              <el-option
                v-for="status in statusOptions"
                :key="status.value"
                :label="status.label"
                :value="status.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :xs="24" :sm="12">
          <el-form-item label="优先级" prop="priority">
            <el-select v-model="formData.priority" placeholder="请选择优先级" style="width: 100%">
              <el-option
                v-for="priority in priorityOptions"
                :key="priority.value"
                :label="priority.label"
                :value="priority.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <el-col :xs="24" :sm="12">
          <el-form-item label="负责人" prop="member_id">
            <el-select v-model="formData.member_id" placeholder="请选择负责人" style="width: 100%">
              <el-option
                v-for="member in familyMembers"
                :key="member.id"
                :label="member.full_name || member.username"
                :value="member.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :xs="24" :sm="12">
          <el-form-item label="重复类型" prop="repeat_type">
            <el-select v-model="formData.repeat_type" placeholder="请选择重复类型" style="width: 100%">
              <el-option
                v-for="repeat in repeatOptions"
                :key="repeat.value"
                :label="repeat.label"
                :value="repeat.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16" v-if="formData.repeat_type !== 'none'">
        <el-col :xs="24" :sm="12">
          <el-form-item label="重复截止" prop="repeat_until">
            <el-date-picker
              v-model="formData.repeat_until"
              type="datetime"
              placeholder="选择重复截止时间"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <el-col :xs="24" :sm="12">
          <el-form-item label="启用提醒">
            <el-switch v-model="formData.is_reminder_enabled" />
          </el-form-item>
        </el-col>
        
        <el-col :xs="24" :sm="12" v-if="formData.is_reminder_enabled">
          <el-form-item label="提醒时间" prop="reminder_minutes">
            <el-select v-model="formData.reminder_minutes" placeholder="请选择提醒时间" style="width: 100%">
              <el-option label="5分钟前" :value="5" />
              <el-option label="10分钟前" :value="10" />
              <el-option label="15分钟前" :value="15" />
              <el-option label="30分钟前" :value="30" />
              <el-option label="1小时前" :value="60" />
              <el-option label="2小时前" :value="120" />
              <el-option label="1天前" :value="1440" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="位置" prop="location">
        <el-input
          v-model="formData.location"
          placeholder="请输入位置信息"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="参与者">
        <el-select
          v-model="formData.participant_ids"
          multiple
          placeholder="请选择参与者"
          style="width: 100%"
        >
          <el-option
            v-for="member in familyMembers"
            :key="member.id"
            :label="member.full_name || member.username"
            :value="member.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          placeholder="请输入日程描述"
          :rows="3"
          maxlength="2000"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="备注">
        <el-input
          v-model="formData.notes"
          type="textarea"
          placeholder="请输入备注信息"
          :rows="2"
          maxlength="2000"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          {{ loading ? '更新中...' : '更新' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue';
import { useScheduleStore } from '@/stores/schedule';
import { useFamilyStore } from '@/stores/family';
import { useScreenSize } from '@/utils/responsive';
import type { FormInstance, FormRules } from 'element-plus';
import type { ScheduleUpdate } from '@/types/schedule';
import { ScheduleStatus, SchedulePriority, ScheduleRepeatType } from '@/types/schedule';

interface Props {
  visible: boolean;
  scheduleId: number | null;
}

interface Emits {
  (e: 'update:visible', value: boolean): void;
  (e: 'success'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const scheduleStore = useScheduleStore();
const familyStore = useFamilyStore();
const { isMobile, dialogWidth } = useScreenSize();

const formRef = ref<FormInstance>();
const loading = ref(false);

const formData = reactive<ScheduleUpdate>({
  title: '',
  description: '',
  start_time: '',
  end_time: '',
  status: ScheduleStatus.PENDING,
  priority: SchedulePriority.MEDIUM,
  repeat_type: ScheduleRepeatType.NONE,
  repeat_until: null,
  is_reminder_enabled: false,
  reminder_minutes: null,
  location: '',
  notes: '',
  member_id: 0,
  participant_ids: [],
});

const rules: FormRules = {
  title: [
    { required: true, message: '请输入日程标题', trigger: 'blur' },
    { min: 1, max: 200, message: '日程标题长度在 1 到 200 个字符', trigger: 'blur' },
  ],
  start_time: [
    { required: true, message: '请选择开始时间', trigger: 'change' },
  ],
  end_time: [
    { required: true, message: '请选择结束时间', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (formData.start_time && value && new Date(value) <= new Date(formData.start_time)) {
          callback(new Error('结束时间必须晚于开始时间'));
        } else {
          callback();
        }
      },
      trigger: 'change',
    },
  ],
  member_id: [
    { required: true, message: '请选择负责人', trigger: 'change' },
  ],
  reminder_minutes: [
    {
      validator: (rule, value, callback) => {
        if (formData.is_reminder_enabled && !value) {
          callback(new Error('请选择提醒时间'));
        } else {
          callback();
        }
      },
      trigger: 'change',
    },
  ],
};

const statusOptions = [
  { value: ScheduleStatus.PENDING, label: '待处理' },
  { value: ScheduleStatus.IN_PROGRESS, label: '进行中' },
  { value: ScheduleStatus.COMPLETED, label: '已完成' },
  { value: ScheduleStatus.CANCELLED, label: '已取消' },
];

const priorityOptions = [
  { value: SchedulePriority.LOW, label: '低' },
  { value: SchedulePriority.MEDIUM, label: '中' },
  { value: SchedulePriority.HIGH, label: '高' },
  { value: SchedulePriority.URGENT, label: '紧急' },
];

const repeatOptions = [
  { value: ScheduleRepeatType.NONE, label: '不重复' },
  { value: ScheduleRepeatType.DAILY, label: '每天' },
  { value: ScheduleRepeatType.WEEKLY, label: '每周' },
  { value: ScheduleRepeatType.MONTHLY, label: '每月' },
  { value: ScheduleRepeatType.YEARLY, label: '每年' },
];

const familyMembers = computed(() => familyStore.familyMembers);

const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
});

const loadScheduleData = () => {
  const schedule = scheduleStore.currentSchedule;
  if (schedule) {
    Object.assign(formData, {
      title: schedule.title,
      description: schedule.description,
      start_time: schedule.start_time,
      end_time: schedule.end_time,
      status: schedule.status,
      priority: schedule.priority,
      repeat_type: schedule.repeat_type,
      repeat_until: schedule.repeat_until,
      is_reminder_enabled: schedule.is_reminder_enabled,
      reminder_minutes: schedule.reminder_minutes,
      location: schedule.location,
      notes: schedule.notes,
      member_id: schedule.member_id,
      participant_ids: schedule.participants?.map(p => p.member_id) || [],
    });
  }
};

const resetForm = () => {
  Object.assign(formData, {
    title: '',
    description: '',
    start_time: '',
    end_time: '',
    status: ScheduleStatus.PENDING,
    priority: SchedulePriority.MEDIUM,
    repeat_type: ScheduleRepeatType.NONE,
    repeat_until: null,
    is_reminder_enabled: false,
    reminder_minutes: null,
    location: '',
    notes: '',
    member_id: 0,
    participant_ids: [],
  });
  
  formRef.value?.clearValidate();
};

const handleClose = () => {
  visible.value = false;
  resetForm();
};

const handleSubmit = async () => {
  if (!formRef.value || !props.scheduleId) return;

  try {
    await formRef.value.validate();
    loading.value = true;

    await scheduleStore.updateSchedule(props.scheduleId, formData);
    
    emit('success');
    handleClose();
  } catch (error) {
    console.error('Update schedule error:', error);
  } finally {
    loading.value = false;
  }
};

watch(() => props.visible, (newValue) => {
  if (newValue && props.scheduleId) {
    // 每次打开模态框时都重新加载家庭成员数据以确保数据是最新的
    familyStore.fetchFamilyMembers().catch((error) => {
      console.error('Failed to fetch family members:', error);
    });
    loadScheduleData();
  }
});
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}

:deep(.mobile-dialog) {
  .el-dialog {
    margin: 0 !important;
    margin-top: 10px !important;
    border-radius: var(--el-border-radius-small);
  }
  
  .el-dialog__body {
    padding: 16px;
  }
}
</style>